﻿#region
using System.Collections.Generic;
using System.IO;
using System.Text;
using HtmlAgilityPack;

#endregion

namespace EndlessDownloader.Engine
{
    public class ImageSourceParser
    {
        #region singleton
        private static ImageSourceParser _instance;

        public static ImageSourceParser Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new ImageSourceParser();
                return _instance;
            }
        }

        private ImageSourceParser()
        {
        }
        #endregion

        public List<string> ExtractImageUrl(string html, bool noPorn)
        {
            List<string> urls = new List<string>();

            using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(html)))
            {
                HtmlDocument doc = new HtmlDocument();
                doc.Load(stream);

                var nodes = doc.DocumentNode.SelectNodes("//img");

                if (nodes == null)
                    return urls;

                foreach (HtmlNode link in nodes)
                {
                    HtmlAttribute attribute = link.Attributes["src"];

                    if (attribute.Value.Contains("media.tumblr.com") == false)
                        continue;

                    if (attribute.Value.Contains("www.tumblr.com"))
                        continue;

                    if (noPorn && attribute.Value.ToLower().EndsWith("gif"))
                        continue;

                    urls.Add(attribute.Value);
                }
            }

            return urls;
        }
    }
}